package com.itheima.security;

import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Component
public class SpringSecurityUserService implements UserDetailsService {
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    //使用一个map 模拟一个数据库
    public Map map = new HashMap<>();

    public void init(){

        User user1 = new User();
        user1.setUsername("zhangsan");
        user1.setPassword(bCryptPasswordEncoder.encode("1234"));

        User user2 = new User();
        user2.setUsername("lisi");
        user2.setPassword(bCryptPasswordEncoder.encode("1234"));

        map.put(user1.getUsername(),user1);
        map.put(user2.getUsername(),user2);
    }


    /**
     *该方法会在用户提交信息时候执行
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //初始化数据库
        init();

        //模拟从数据库通过用户名查询数据
        User user = (User) map.get(username);

        //给用户设置权限和角色
        ArrayList<GrantedAuthority> list = new ArrayList<>();
        //权限：全大写
        list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        list.add(new SimpleGrantedAuthority("add"));

        //若密码没有加密，，是一个明文密码 需要在密码前加上{noop}
        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),list);
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode("1234");
        String encode1 = passwordEncoder.encode("1234");
        System.out.println(encode);
        System.out.println(encode1);

        boolean flag1 = passwordEncoder.matches("1234", encode);
        boolean flag2 = passwordEncoder.matches("1234", encode);

        System.out.println(flag1);
        System.out.println(flag2);
    }
}
